@file:Suppress("unused")

package com.link.play.fit.ai.base

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.SystemBarStyle
import androidx.activity.enableEdgeToEdge
import androidx.annotation.ColorInt
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
import com.link.play.fit.ai.utils.EventUtils

/**
 *
 * @param VB : ViewBinding
 * 基本的fragment绑定数据
 */

abstract class BaseFragment<VB : ViewBinding>(
    private val bindingInflater: (LayoutInflater, ViewGroup?, Boolean) -> VB,
    private val logEvent: Boolean = true
) : Fragment() {
    protected var _binding: VB? = null
    private var fragmentInit = false
    private var fragmentOnResume = false
    open val TAG = javaClass.simpleName

    //重写binding get()方法不直接暴露真实的可空_binding数据
    @Suppress("MemberVisibilityCanBePrivate")
    val binding: VB
        get() = _binding!!

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = bindingInflater.invoke(inflater, container, false)

        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (logEvent) EventUtils.event("page_$TAG")
    }

    open fun lazyInit() {

    }


    open fun onResumeOneShoot() = Unit

    override fun onResume() {
        if (!fragmentOnResume) {
            onResumeOneShoot()
            fragmentOnResume = true
        }
        if (!fragmentInit) {
            lazyInit()
            fragmentInit = true
        }
        super.onResume()
    }

    override fun onStop() {
        super.onStop()
        fragmentOnResume = false
    }


    override fun onDestroyView() {
        super.onDestroyView()
        //要手动置null防止内存泄漏
        _binding = null
        fragmentInit = false
    }

    fun setStatusBarColor(@ColorInt color: Int = Color.TRANSPARENT, isLight: Boolean = true) {
        activity?.enableEdgeToEdge(
            if (isLight) SystemBarStyle.light(
                color,
                color
            ) else SystemBarStyle.dark(color)
        )
    }
}

inline fun <VB : ViewBinding> BaseFragment<VB>.viewBind(block: VB.() -> Unit) {
    binding.apply(block)
}

inline fun Fragment.goToAc(clazz: Class<out Activity>, block: (Intent.() -> Unit) = {}) {
    context?.startActivity(Intent(context, clazz).apply(block))
}

inline fun Fragment.goToAc(
    clazz: Class<out Activity>,
    options: Bundle? = null,
    block: (Intent.() -> Unit) = {}
) {
    context?.startActivity(Intent(context, clazz).apply(block), options)
}
